#include "app_runner.h"
#include <stdlib.h>
#include <signal.h>
#include "app_router.h"
#include "app_pool.h"
#include "app_serial.h"
#include "log/log.h"

static int is_running = 1;

static void app_runner_exitHandler(int signum)
{
    log_info("Received signal %d, exiting...", signum);
    is_running = 0;
}

void app_runner_run()
{
    // 注册退出逻辑
    signal(SIGINT, app_runner_exitHandler);
    signal(SIGTERM, app_runner_exitHandler);

    // 1. 初始化
    if (app_pool_init(5) < 0)
    {
        log_error("Pool init failed");
        exit(EXIT_FAILURE);
    }
    if (app_router_init() < 0)
    {
        log_error("Router init failed");
        exit(EXIT_FAILURE);
    }
    SerialDevice *dev = app_serial_init("/dev/ttyS1");
    if (app_serial_setConnectionType(dev, TYPE_BT) < 0)
    {
        log_error("Set connection type failed");
        exit(EXIT_FAILURE);
    }
    app_router_registerDevice((Device *)dev);

    // 2. 卡住主线程
    while (is_running)
    {
        usleep(100);
    }

    app_router_deinit();
    app_pool_deinit();
}